package com.shinbada.core.persistence.genrule;

import org.apache.commons.lang.StringUtils;

/**
 * 设置前缀后缀，中间是增长型数字的规则
 *
 * @author initcap
 * @date Created in 2020/11/25 22:33.
 */
public interface IPostPreIdGenRule extends IdGenRule {

    /**
     * @return 获取前缀
     */
    String getPre();

    /**
     * @return 获取后缀
     */
    String getPost();

    /**
     * @return 获取中间数值的长度
     */
    Integer getLength();

    /**
     * @return 获取规则Mapper
     */
    RuleMapper getRuleMapper();

    @Override
    default String genCode() {
        StringBuilder current = new StringBuilder(max());
        while (current.length() < getLength()) {
            current.insert(0, "0");
        }
        return current.insert(0, getPre()).append(getPost()).toString();
    }

    /**
     * @return 获取到当前数据库中主键最大数字
     */
    default String max() {
        String id = getRuleMapper().getMaxIdByCreateTime();
        if (StringUtils.isBlank(id)) {
            return "1";
        }
        String num = id.substring(getPre().length(), getPre().length() + getLength());
        return Integer.parseInt(num) + 1 + "";
    }

}
